package com.kongl.lottery.order.controller;

import com.kongl.lottery.order.entity.Order;
import com.kongl.lottery.order.entity.OrderItem;
import com.kongl.lottery.order.entity.vo.OrderVo;
import com.kongl.lottery.order.repository.OrderRepository;
import com.kongl.lottery.order.util.JsonUtils;
import com.kongl.lottery.order.util.ResponseVo;
import com.kongl.lottery.order.util.UUIDUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;

import java.util.Date;
import java.util.List;

@RestController
public class OrderController {

    @Autowired
    private OrderRepository orderRepository;
    @PostMapping("/save")
    public ResponseVo<Order> save(String uid, String carts){
        Order order=new Order();
        order.setCreateTime(new Date());
        order.setOid(UUIDUtils.getId());
        order.setUid(uid);

        List<OrderItem> orderItems=JsonUtils.parseList(carts,OrderItem.class);
        order.setOrderItems(orderItems);

        orderItems.forEach(orderItem ->{
            orderItem.setItemid(UUIDUtils.getId());
            orderItem.setOid(order.getOid());
            }
        );
        double total = orderItems.stream().mapToDouble(orderItem -> orderItem.getCount() * 2).sum();
        order.setTotal(total);
        orderRepository.save(order);
        return ResponseVo.success(order);
    }

    @PostMapping("")
    public ResponseVo<Order> saveOrder(@RequestBody OrderVo orderVo){
        Order order=new Order();
        order.setCreateTime(new Date());
        order.setOid(UUIDUtils.getId());
        order.setUid(orderVo.getUid());

        List<OrderItem> orderItems=orderVo.getOrderItems();
        orderItems.forEach(orderItem ->{
                    orderItem.setItemid(UUIDUtils.getId());
                    orderItem.setOid(order.getOid());
                }
        );
        double total = orderItems.stream().mapToDouble(orderItem -> orderItem.getCount() * 2).sum();
        order.setTotal(total);
        order.setOrderItems(orderItems);
        //orderRepository.save(order);
        return ResponseVo.success(order);
    }
}
